<?php

namespace App\Console\Commands;

use Illuminate\Support\Facades\Redis;
use App\App\Services\DPService;
use Illuminate\Console\Command;
use Carbon\Carbon;

class DPStatic extends Command
{
    protected $DPService;
    protected $lock;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dpstatic';

    private $lockKey = 'dpStaticProcessStatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '按活动生成大屏静态页';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(DPService $DPService)
    {
        $this->DPService = $DPService;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        echo "按活动生成大屏静态页" . PHP_EOL;
        echo "开始" . PHP_EOL;
        $this->getLock();
        $this->lock();
        if (!$this->isLocked()) {
            $this->DPService->dpStatic();
            $this->unlock();
            echo Carbon::now()->format('Y-m-d H:i:s').PHP_EOL;
        } else {
            sleep(5);
            $this->unlock();
            echo "已有其他进程在运行" . PHP_EOL;
        }
        echo "完成" . PHP_EOL;
        sleep(300);
    }

    private function getLock()
    {
        $this->lock = Redis::get($this->lockKey);
    }

    private function lock()
    {
        Redis::set($this->lockKey, 'running');
    }

    private function unlock()
    {
        Redis::set($this->lockKey, 'exit');
    }

    private function isLocked()
    {
        return $this->lock === 'running';
    }
}
